<?php
namespace app\store\controller\wechat;
use app\store\controller\Controller;
use app\store\model\WechatBatchSend as WechatBatchSendModel;
use app\store\model\Wechat as WechatModel;

/**
 * 微信群发消息控制器
 */
class Send extends Controller
{
	/**
     * 首页
     */
    public function index()
    {
        $model = new WechatBatchSendModel;
        $list = $model->getList();
        return $this->fetch('index', compact('list'));
    }
	
	/**
     * 添加
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            return $this->fetch('add');
        }
		//全局验证
		if($err = checking(1)){
			return $this->renderError($err);
		}
		$wechat = WechatModel::detail();
        if(empty($wechat['app_id'])){
            return $this->renderError('还未绑定公众号');
        }
        $model = new WechatBatchSendModel;
        if ($model->add($this->postData('msg'))) {
            return $this->renderSuccess('添加成功', url('wechat.send/index'));
        }
        $error = $model->getError() ?: '添加失败';
        return $this->renderError($error);
    }

    /**
     * 删除
     */
    public function delete($wechat_batch_send_id)
    {
		//全局验证
		if($err = checking(1)){
			return $this->renderError($err);
		}
        $model = WechatBatchSendModel::get($wechat_batch_send_id);
        if ($model->remove()) {
            return $this->renderSuccess('删除成功');
        }
        $error = $model->getError() ?: '删除失败';
        return $this->renderError($error);
    }

    /**
     * 编辑
     */
    public function edit($wechat_batch_send_id)
    {
        $model = WechatBatchSendModel::get($wechat_batch_send_id);
        if (!$this->request->isAjax()) {
            return $this->fetch('edit', compact('model'));
        }
		//全局验证
		if($err = checking(1)){
			return $this->renderError($err);
		}
		$wechat = WechatModel::detail();
        if(empty($wechat['app_id'])){
            return $this->renderError('还未绑定公众号');
        }
        // 更新记录
        if ($model->edit($this->postData('msg'))) {
            return $this->renderSuccess('更新成功', url('wechat.send/index'));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }
	
	/**
     * 群发
     */
    public function send($wechat_batch_send_id)
    {
		//全局验证
		if($err = checking(1)){
			return $this->renderError($err);
		}
        $model = WechatBatchSendModel::get($wechat_batch_send_id);
        if ($model->send()){
            return $this->renderSuccess('群发成功');
        }
        $error = $model->getError() ?: '群发失败';
        return $this->renderError($error);
    }

}
